/*

 
 Copyright (C) 2012 Apple Inc. All Rights Reserved.
 
 */

#import <Foundation/Foundation.h>

#import "LAGOverLapImageScrollView.h"
#import "UIView+FrameProperties.h"
#import "OverLapImageLay.h"

#pragma mark -

@interface LAGOverLapImageScrollView () <UIScrollViewDelegate>
{
    CGSize _imageSize;
//    UIView *_actualZoomView;
    __weak MKMapView *_syncMovingMapView;
    
    OverLapImageLay *_testLayer;
   
    CLLocationCoordinate2D _orgCord;
    CLLocationCoordinate2D _rightBottomCord;
    
}

@end

@implementation LAGOverLapImageScrollView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.alpha = 0.6;
        self.showsVerticalScrollIndicator = YES;
        self.showsHorizontalScrollIndicator = YES;
        self.bouncesZoom = YES;
        self.zoomState = YES;
        self.decelerationRate = UIScrollViewDecelerationRateFast;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.delegate = self;
        UITapGestureRecognizer *doubleTpa = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAutoZoom:)];
        doubleTpa.numberOfTapsRequired = 2;
        [self addGestureRecognizer:doubleTpa];
    
    }
    return self;
}

- (void)layoutSubviews 
{
    [super layoutSubviews];
    
}


-(void)tapAutoZoom:(UITapGestureRecognizer *)rgz
{
    if(self.zoomScale > 1.1 || self.zoomScale - self.minimumZoomScale < 0.001)
        self.zoomScale = 1;
    else
        self.zoomScale = self.minimumZoomScale;
}

-(CGSize)contentSizeForSubViewSize
{
 //   return _imageSize;// CGSizeMake(99999999, 99999999);
    
    CGSize s = CGSizeMake(_imageSize.width*self.zoomScale, _imageSize.height*self.zoomScale);
   return  CGSizeMake(s.width+(self.frame.size.width-10)*2, s.height+(self.frame.size.height-10)*2);
}

-(UIView *)viewToZoom
{
    return self.zoomImageView;
}

#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    if ( self.zoomState ) {
        return [self viewToZoom];
    }
    return nil;
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(nullable UIView *)view
{
   //     NSLog(@"==== center(%f,%f) offset:(%f,%f) csize(w:%f h:%f) scale:%f",view.centerX,view.centerY,self.contentOffset.x,self.contentOffset.y,self.contentSize.width,self.contentSize.height,self.zoomScale);

}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    UIView *subView = [self viewToZoom];
 //   NSLog(@"     center(%f,%f) offset:(%f,%f) csize(w:%f h:%f) scale:%f",subView.centerX,subView.centerY,self.contentOffset.x,self.contentOffset.y,self.contentSize.width,self.contentSize.height,self.zoomScale);

    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;

    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;

    subView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                 scrollView.contentSize.height * 0.5 + offsetY);
    
}


- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
//    UIView *subView = [self viewToZoom];
//    NSLog(@"|||| center(%f,%f) offset:(%f,%f) csize(w:%f h:%f) scale:%f",subView.centerX,subView.centerY,self.contentOffset.x,self.contentOffset.y,self.contentSize.width,self.contentSize.height,self.zoomScale);

    [self replaceWithZooming:scrollView withView:view atScale:scrollView.zoomScale];
}

-(void)replaceWithZooming:(UIScrollView *)scrollView withView:(UIView *)viewActuaZoom atScale:(CGFloat)scale
{
    UIView *view = viewActuaZoom;//self.zoomImageView;
    CGPoint preOffset = scrollView.contentOffset;
    CGSize ctSize = [self contentSizeForSubViewSize];
    /*
     1、view的原点相对于scrollView原点的偏移 poff1;
     2、获取新的ctSize
     3、view的中心至于新content的中心
     4、计算view的原点对于scrollView原点的偏移 poff2;
     4、新的offset即  poff2-poff1
     */
    CGPoint poff1 = CGPointMake(view.x-preOffset.x, view.y-preOffset.y);
    self.contentSize = ctSize;
    view.center = CGPointMake(ctSize.width/2, ctSize.height/2);
    CGPoint poff2 = CGPointMake(view.x-preOffset.x, view.y-preOffset.y);
    CGPoint newOffset = CGPointMake(preOffset.x+(poff2.x-poff1.x), preOffset.y+(poff2.y-poff1.y));
    scrollView.contentOffset = newOffset;
}

//-(void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    UIView *subView = [self viewToZoom];
//    NSLog(@">>>> center(%f,%f) offset:(%f,%f) csize(w:%f h:%f) scale:%f",subView.centerX,subView.centerY,self.contentOffset.x,self.contentOffset.y,self.contentSize.width,self.contentSize.height,self.zoomScale);
//
//}


- (void)displayImage:(UIImage *)image
{
    if(self.zoomImageView == nil)
    {
        self.zoomImageView = [[UIImageView alloc]initWithImage:image];
        self.zoomImageView.backgroundColor = [UIColor clearColor];
        [self addSubview:self.zoomImageView];
    }
    else
        [self.zoomImageView setImage:image];
    
    
    _imageSize = image.size;
    self.zoomScale = 1.0;

    CGSize ctSize = [self contentSizeForSubViewSize];
    self.contentSize = ctSize;
    self.contentOffset = CGPointMake(self.contentSize.width/2-self.frame.size.width/2, self.contentSize.height/2-self.frame.size.height/2);
    self.zoomImageView.frame = CGRectMake((self.contentSize.width-_imageSize.width)/2, (self.contentSize.height-_imageSize.height)/2, _imageSize.width, _imageSize.height);
    
    self.maximumZoomScale = 99999999;
    self.minimumZoomScale = MIN(1,(self.frame.size.width/_imageSize.width)*0.00001);
    
}

#pragma mark-
-(void)startSynchronizeMovingViewMapView:(MKMapView *)mapView
{
    self.userInteractionEnabled = NO;
   // self.hidden = YES;

    _syncMovingMapView = mapView;
    CGRect imageRect = self.zoomImageView.frame;
    
#if 1 //采用这种方式转换坐标会更准确
    _orgCord = [_syncMovingMapView convertPoint:imageRect.origin toCoordinateFromView:self];
    _rightBottomCord = [_syncMovingMapView
                                              convertPoint:CGPointMake(imageRect.origin.x+imageRect.size.width, imageRect.origin.y+imageRect.size.height)
                                              toCoordinateFromView:self];
#else //用这种方式转换，在地图层级比较低的情况，越靠近两极偏差越大
    MKCoordinateRegion reg = [_syncMovingMapView convertRect:imageRect toRegionFromView:self];
    CLLocationCoordinate2D orgCord = CLLocationCoordinate2DMake(reg.center.latitude-reg.span.latitudeDelta/2, reg.center.longitude-reg.span.longitudeDelta/2);
    CLLocationCoordinate2D rightBottomCord = CLLocationCoordinate2DMake(reg.center.latitude+reg.span.latitudeDelta/2, reg.center.longitude+reg.span.longitudeDelta/2);
#endif
    MKMapPoint mkOrg = MKMapPointForCoordinate(_orgCord);
    MKMapPoint mkrightBottom = MKMapPointForCoordinate(_rightBottomCord);
    MKMapRect imageOccupiedMapRect = MKMapRectMake(mkOrg.x, mkOrg.y, mkrightBottom.x-mkOrg.x, mkrightBottom.y-mkOrg.y);
   

    if(_testLayer)
        [_syncMovingMapView removeOverlay:_testLayer];
    _testLayer = [[OverLapImageLay alloc]initWithImage:self.zoomImageView.image onMapRect:imageOccupiedMapRect alpha:self.alpha];
    [_syncMovingMapView addOverlay:_testLayer];
    
}

-(void)releaseSynchronizeMoving
{
    if(!_syncMovingMapView)
        return;
    
    self.userInteractionEnabled = YES;
    self.hidden = NO;
    
    CGPoint p1 = [_syncMovingMapView convertCoordinate:_orgCord toPointToView:self];
    CGPoint p2 = [_syncMovingMapView convertCoordinate:_rightBottomCord toPointToView:self];
    NSLog(@"NEW   RECT(%f,%f,%f,%f)",p1.x,p1.y,p2.x-p1.x,p2.y-p1.y);
    NSLog(@"IMAGE RECT(%f,%f,%f,%f)",self.zoomImageView.x,self.zoomImageView.y,self.zoomImageView.width,self.zoomImageView.height);
    CGFloat k = fabs(p2.x-p1.x)/self.zoomImageView.width;
    CGFloat newScale = self.zoomScale*k;
    NSLog(@"prescale %f newScale %f",self.zoomScale,newScale);
 //   self.zoomScale = newScale;
    
 //   [_syncMovingMapView removeOverlay:_testLayer];
    _syncMovingMapView = nil;
    
    

}

//-(void)syncMovemoentForMapView:(MKMapView *)mapView
//{
//    id mapGestureController = [mapView valueForKey:@"gestureController"];
//    [self.panGestureRecognizer addTarget:mapGestureController action:@selector(handlePan:)];
//    [self.pinchGestureRecognizer addTarget:mapGestureController action:@selector(handlePinch:)];
//}
//
//-(void)unsyncMoveMentForMapView:(MKMapView *)mapView
//{
//    NSMutableArray *panTargets = [self.panGestureRecognizer valueForKey:@"_targets"];
//    NSMutableArray *pinchTargets = [self.pinchGestureRecognizer valueForKey:@"_targets"];
//    if(panTargets.count > 1)
//        [panTargets removeObjectAtIndex:1];
//    if(pinchTargets.count > 1)
//        [pinchTargets removeObjectAtIndex:1];
//}

#if 0
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if(_syncMovingMapView )
    {
        UITouch *touch = [touches anyObject];
        
        CGPoint p =  [touch locationInView:self];
        CGPoint prP = [touch previousLocationInView:self];
        CGPoint offset = CGPointMake(p.x-prP.x, p.y-prP.y);
        CGPoint ctOff = self.contentOffset;
        self.contentOffset = CGPointMake(ctOff.x-offset.x, ctOff.y-offset.y);
        [self moveMapWithPixelOffset:offset];
        
    }
}

-(void)moveMapWithPixelOffset:(CGPoint)offset
{
    //移动坐标会有比较大的误差
    CGPoint preCenterPt = [_syncMovingMapView convertCoordinate:_syncMovingMapView.centerCoordinate toPointToView:_syncMovingMapView];
    CLLocationCoordinate2D centerCord = [_syncMovingMapView convertPoint:CGPointMake(preCenterPt.x-offset.x, preCenterPt.y-offset.y) toCoordinateFromView:_syncMovingMapView];
    [_syncMovingMapView setCenterCoordinate:centerCord];
    
}

#endif 

@end
